#include "xmlhelpers.h"

#include <cstdlib>

void XMLGetValue (std::string & valbuf, rapidxml::xml_node<> * node) throw(Error) {
	if (!node) {
		throw Error("XMLGetValue argument is NULL");
	}
	char * tmp = node->value();
	if (!tmp) {
		throw Error("Node value(); retruned NULL");
	} else {
		valbuf = tmp;
	}
}
void XMLGetValue (std::string & valbuf, rapidxml::xml_attribute<> * attr) throw(Error) {
	if (!attr) {
		throw Error("XMLGetValue argument is NULL");
	}
	char * tmp = attr->value();
	if (!tmp) {
		throw Error("Node value(); retruned NULL");
	} else {
		valbuf = tmp;
	}
}
void XMLGetValue (std::string & valbuf, rapidxml::xml_node<> * node, const std::string & attr_name) throw(Error) {
	if (!node) {
		throw Error("XMLGetValue argument is NULL" );
	}
	rapidxml::xml_attribute<> * attr = node->first_attribute(attr_name.c_str());
	if (!attr) {
		throw Error("There is no such attribute", node->name());
	}
	char * tmp = attr->value();
	if (!tmp) {
		throw Error("Node value(); retruned NULL" );
	} else {
		valbuf = tmp;
	}
}

void XMLGetValue (int & valbuf, rapidxml::xml_node<> * node) throw(Error) {
	std::string tmp;
	XMLGetValue(tmp, node);
	valbuf = atoi(tmp.c_str());
}

void XMLGetValue (int & valbuf, rapidxml::xml_attribute<> * attr) throw(Error) {
	std::string tmp;
	XMLGetValue(tmp, attr);
	valbuf = atoi(tmp.c_str());
}

void XMLGetValue (int & valbuf, rapidxml::xml_node<> * node, const std::string & attr_name) throw(Error) {
	std::string tmp;
	XMLGetValue(tmp, node, attr_name);
	valbuf = atoi(tmp.c_str());
}

void XMLGetValue (bool& valbuf, rapidxml::xml_node<> * node) throw(Error) {
	std::string tmp;
	XMLGetValue(tmp, node);
	if (tmp == "true") {
		valbuf = true;
	} else {
		valbuf = false;
	}
}

void XMLGetValue (bool& valbuf, rapidxml::xml_attribute<> * attr) throw(Error) {
	std::string tmp;
	XMLGetValue(tmp, attr);
	if (tmp == "true") {
		valbuf = true;
	} else {
		valbuf = false;
	}
}

void XMLGetValue (bool& valbuf, rapidxml::xml_node<> * node, const std::string & attr_name) throw(Error) {
	std::string tmp;
	XMLGetValue(tmp, node, attr_name);
	if (tmp == "true") {
		valbuf = true;
	} else {
		valbuf = false;
	}
}

rapidxml::xml_node<> * XMLGetNode (rapidxml::xml_document<> & xml, const std::string & node_name) throw (Error) {
	rapidxml::xml_node<> * tmp = xml.first_node(node_name.c_str());
	if (!tmp) {
		throw Error("There is no such node", node_name);
	}
	return tmp;
}

rapidxml::xml_node<> * XMLGetNode (rapidxml::xml_node<> * node, const std::string & node_name) throw (Error) {
	if (!node) {
		throw Error("There is no nodes of NULL" );
	}
	rapidxml::xml_node<> * tmp = node->first_node(node_name.c_str());
	if (!tmp) {
		throw Error("There is no such nodes", node_name);
	}
	return tmp;
}

rapidxml::xml_node<> * XMLGetSibling (rapidxml::xml_node<> * node) throw(Error) {
	if (!node) {
		throw Error("There is siblings of NULL. Forever alone." );
	}
	return node->next_sibling(node->name());
}

